package com.ncloud.param.service.impl;

import java.util.List;

import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.utils.RedisUtils;
import com.ncloud.param.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.exception.UserException;
import com.ncloud.param.entity.Tag;
import com.ncloud.param.mapper.TagMapper;
import org.springframework.util.StringUtils;

@Service
public class TagServiceImpl implements TagService {
	
	@Autowired
	private TagMapper mapper;
	@Autowired
	private RedisUtils redisUtils;

	private static final Long expireTime= 7*24*60*60L;
	@Override
	public JSONArray getTagInfo(JSONObject json) {
		if(!json.containsKey("tagCode"))
			throw new UserException();
		String tagCode = json.getString("tagCode");
		String key = "tag_tagCode_"+tagCode;
		if(redisUtils.exists(key)){
			JSONArray info = redisUtils.getBean(key,JSONArray.class);
			return info;
		}else{
			List<Tag> tags = mapper.getTags(tagCode);
			JSONArray array = JSON.parseArray(JSON.toJSONString(tags));
			redisUtils.set(key,array,expireTime);
			return array;
		}
	}

	public JSONObject getTagInfoOne(String tagCode){
		if(StringUtils.isEmpty(tagCode))
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"tagCode参数不能为空！");
		String key = "tag_one_"+tagCode;
		if(redisUtils.exists(key)){
			JSONObject info = redisUtils.getBean(key,JSONObject.class);
			return info;
		}else{
			Tag  tag = mapper.getTagOne(tagCode);
			JSONObject object = JSON.parseObject(JSON.toJSONString(tag));
			redisUtils.set(key,object,expireTime);
			return object;
		}
	}

}
